import $ from 'jquery'
import { Label, LabelEvent, LabelSubscriber } from './js/bajaui_Label.js'
import Image from './js/bajaui_Image.js'
import {
  popupPX,
  popupPXEvent,
  popupPXSubscriber,
} from './js/sensetechKitPx_PopupPx.js'
import { computerWidthHeightTopLeft } from './js/unit.js'
import transfromFun from './js/transform.js'
import './styles/style.scss'
// import loadingimg  from './loading.gif';

var bajaui_Label = Label
var bajaui_Label_Event = LabelEvent
var bajaui_Picture = Image
var sensetechKitPx_PopupPx = popupPX
var sensetechKitPx_PopupPx_Event = popupPXEvent

$(function () {
  console.log(1123131)
  // $("body").append(`<div id="loading">
  //                         <img src="${"/file/dist/"+loadingimg}" alt="">
  //                     </div>`);
  // var px = new PxEngine();
  //ajax get请求px页面，返回的json数据
  var address = location.hostname + ':' + location.port
  $.ajax({
    url: 'http://' + address + '/px?path=file:^PxFile.px&domId=main',
    success: function (data) {
      var json = data

      var dom = JsonDecoder(json)
      //  解析json结果
      $('#main').append(dom)
      transfromFun() // 缩放的函数
      subscribe(json) // webSocket链接
    },
  })

  document.oncontextmenu = function () {
    return false
  }
})

var websocket = ''

function subscribe(json) {
  if ('WebSocket' in window) {
    var address = location.hostname + ':' + location.port
    // address = "192.168.1.190:8848";
    websocket = new WebSocket('ws://' + address + '/wsPxEngine/')
  } else {
    alert('当前浏览器 Not support websocket')
  }
  //连接发生错误的回调方法
  websocket.onerror = function () {}
  //连接成功建立的回调方法
  websocket.onopen = function () {
    // console.log('websocket链接成功');
    // 链接成功之后发送心跳包
    send({
      type: 'heartbeat',
    })
    var heartBeatInt = setInterval(function () {
      send({
        type: 'heartbeat',
      })
    }, 5 * 1000)
    bindEvent(json) //开始订阅事件
  }
  //接收到消息的回调方法
  websocket.onmessage = function (event) {
    // console.log("这里是index.js中的",event.data);
    var nowData = JSON.parse(event.data)
    if (nowData.class == 'popup') {
      popupPXSubscriber(nowData)
    } else if (nowData.class == 'label') {
      LabelSubscriber(nowData)
    }
    // $("#"+nowData.id).text(nowData.value + nowData.unit);
  }
  //连接关闭的回调方法
  websocket.onclose = function () {}
  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    closeWebSocket()
  }
}

//关闭WebSocket连接
function closeWebSocket() {
  websocket.close()
}
//发送消息
function send(message) {
  websocket.send(JSON.stringify(message))
}

/**
 * 对事件绑定
 *
 * @param {*} data  json数据
 * @returns Dom数据
 */
function bindEvent(data) {
  try {
    //获取数据的类型，通过":"截取,e.g:data.type=bajaui:Label
    if (
      data.type.indexOf('bajaui:') == -1 &&
      data.type.indexOf('sensetechKitPx:') == -1
    ) {
      return
    }
    var typeClass = data.type.replace(':', '_') + '_Event'
    //获取回调
    var callback = eval(typeClass)
    callback(data)
  } catch (error) {
    return ''
  }
}

/**
 * json数据data进行解析
 *
 * @param {*} data  json数据
 * @returns Dom数据
 */
function JsonDecoder(data) {
  try {
    //获取数据的类型，通过":"截取,e.g:data.type=bajaui:Label
    if (
      data.type.indexOf('bajaui:') == -1 &&
      data.type.indexOf('sensetechKitPx:') == -1
    ) {
      return
    }
    var typeClass = data.type.replace(':', '_')

    //获取回调
    var callback = eval(typeClass)

    return callback(data)
  } catch (error) {
    return ''
  }
}

/**
 * render子类
 * @param {*} children 子类数组
 * @param {*} dom  dom节点数据
 */
function renderChildren(children) {
  var dom = ''
  for (var i = 0; i < children.length; i++) {
    dom += JsonDecoder(children[i])
  }
  return dom
}

function bajaui_CanvasPane(data) {
  let dom = ''
  computerWidthHeightTopLeft(data)

  dom +=
    '<div class="canvasDom"  style="transform-origin:left top;width:' +
    window.innerWidth +
    'px; height:' +
    window.innerHeight +
    'px;background: ' +
    data.background +
    ';" >'
  // dom += transformScale(data);
  dom +=
    '  <div id="' +
    data.id +
    '"  data-name = "scale"  style="transform-origin: left top; ' +
    transformScale(data) +
    ';width:' +
    data.width +
    'px; height:' +
    data.height +
    'px;">'
  dom += renderChildren(data.childWidgets)
  dom += '  </div>'
  dom += '</div>'
  return dom
}
// 计算缩放比
function transformScale(data) {
  var str = ''
  if (data.scale == 'none') {
    var translateX =
      window.innerWidth < data.width
        ? 0 + ','
        : (window.innerWidth - data.width) / 2 + 'px,'
    var translateY =
      window.innerHeight < data.height
        ? 0
        : (window.innerHeight - data.height) / 2 + 'px'
    var scaleX = 1
    var scaleY = 1
    return (
      'transform:translate(' +
      translateX +
      translateY +
      ') scale(' +
      scaleX +
      ',' +
      scaleY +
      ')'
    )
  } else if (data.scale == 'Fit') {
    var scaleXAndtranslateX = computerFix(
      window.innerWidth,
      data.width,
      data.maxScaleFactor,
      data.minScaleFactor
    )
    var scaleX = scaleXAndtranslateX.scale
    var translateX = scaleXAndtranslateX.translate
    var scaleYAndtranslateY = computerFix(
      window.innerHeight,
      data.height,
      data.maxScaleFactor,
      data.minScaleFactor
    )
    var scaleY = scaleYAndtranslateY.scale
    var translateY = scaleYAndtranslateY.translate
    return (
      'transform:translate(' +
      translateX +
      ',' +
      translateY +
      ') scale(' +
      scaleX +
      ',' +
      scaleY +
      ')'
    )
  } else if (data.scale == 'Fit Ratio') {
    var allData = computerFixRatio(data)
    var scale = allData.scale
    var translateX = allData.translateX
    var translateY = allData.translateY
    return (
      'transform:translate(' +
      translateX +
      ',' +
      translateY +
      ') scale(' +
      scale +
      ',' +
      scale +
      ')'
    )
  } else if (data.scale == 'Fit Width') {
    var allData = computerFixWidth(data)
    var scaleX = allData.scaleX
    var scaleY = allData.scaleY
    var translateX = allData.translateX
    var translateY = allData.translateY
    return (
      'transform:translate(' +
      translateX +
      ',' +
      translateY +
      ') scale(' +
      scaleX +
      ',' +
      scaleY +
      ')'
    )
  } else if (data.scale == 'Fit Height') {
    var allData = computerFixHeight(data)
    var scaleX = allData.scaleX
    var scaleY = allData.scaleY
    var translateX = allData.translateX
    var translateY = allData.translateY
    return (
      'transform:translate(' +
      translateX +
      ',' +
      translateY +
      ') scale(' +
      scaleX +
      ',' +
      scaleY +
      ')'
    )
  }
}
// 根绝不同的情况，计算出来的缩放比，还有位移量
function computerFix(windowWidth, dataWidth, max, min) {
  if (windowWidth > dataWidth) {
    if (windowWidth / dataWidth >= max) {
      var scaleX = max
      var translateX = (windowWidth - max * dataWidth) / 2 + 'px'
    } else {
      var scaleX = (windowWidth / dataWidth).toFixed(5)
      var translateX = 0
    }
  } else {
    if (windowWidth / dataWidth <= min) {
      var scaleX = min
      var translateX = 0
    } else {
      var scaleX = (windowWidth / dataWidth).toFixed(5)
      var translateX = 0
    }
  }
  return {
    scale: scaleX,
    translate: translateX,
  }
}

function computerFixRatio(data) {
  var scaleX = window.innerWidth / data.width

  var scaleY = window.innerHeight / data.height

  var scale = Math.min(scaleX, scaleY)
  if (scale <= data.maxScaleFactor && scale >= data.minScaleFactor) {
    scale = scale
  } else if (scale > data.maxScaleFactor) {
    scale = data.maxScaleFactor
  } else if (scale < data.minScaleFactor) {
    scale = data.minScaleFactor
  }
  if (data.width * scale <= window.innerWidth) {
    var translateX = (window.innerWidth - data.width * scale) / 2 + 'px'
  } else if (data.width * scale > window.innerWidth) {
    var translateX = 0
  }
  if (data.height * scale <= window.innerHeight) {
    var translateY = (window.innerHeight - data.height * scale) / 2 + 'px'
  } else {
    var translateY = 0
  }
  return {
    scale: scale,
    translateX: translateX,
    translateY: translateY,
  }
}

function computerFixWidth(data) {
  var scaleY = 1
  var scaleX = window.innerWidth / data.width
  if (scaleX >= data.minScaleFactor && scaleX <= data.maxScaleFactor) {
    scaleX = scaleX
  } else if (scaleX > data.maxScaleFactor) {
    scaleX = data.maxScaleFactor
  } else if (scaleX < data.minScaleFactor) {
    scaleX = data.minScaleFactor
  }
  if (data.width * scaleX >= window.innerWidth) {
    var translateX = 0
  } else {
    var translateX = (window.innerWidth - data.width * scaleX) / 2 + 'px'
  }
  if (data.height >= window.innerWidth) {
    var translateY = 0
  } else {
    var translateY = (window.innerHeight - data.height) / 2 + 'px'
  }
  return {
    scaleX: scaleX,
    scaleY: scaleY,
    translateX: translateX,
    translateY: translateY,
  }
}

function computerFixHeight(data) {
  var scaleX = 1
  var scaleY = window.innerHeight / data.height
  if (scaleY >= data.minScaleFactor && scaleY <= data.maxScaleFactor) {
    scaleY = scaleY
  } else if (scaleY > data.maxScaleFactor) {
    scaleY = data.maxScaleFactor
  } else if (scaleY < data.minScaleFactor) {
    scaleY = data.minScaleFactor
  }
  if (data.height * scaleY >= window.innerHeight) {
    var translateY = 0
  } else {
    var translateY = (window.innerHeight - data.height * scaleY) / 2 + 'px'
  }
  if (data.width >= window.innerWidth) {
    var translateX = 0
  } else {
    var translateX = (window.innerWidth - data.width) / 2 + 'px'
  }
  return {
    scaleX: scaleX,
    scaleY: scaleY,
    translateX: translateX,
    translateY: translateY,
  }
}

//ScrollPane
function bajaui_ScrollPane(data) {
  let dom = ''
  dom +=
    '<div style="width:' +
    window.innerWidth +
    'px; height:' +
    window.innerHeight +
    'px;overflow:hidden;" >'
  dom += renderChildren(data.childWidgets)
  dom += '</div>'
  return dom
}
function bajaui_ScrollPane_Event(data) {
  //
  eventChildren(data.childWidgets)
}
function bajaui_CanvasPane_Event(data) {
  eventChildren(data.childWidgets)
}
function eventChildren(children) {
  for (var i = 0; i < children.length; i++) {
    bindEvent(children[i])
  }
}

//ValueBinding
function ValueBinding(data) {
  return ''
}

export { send }
